<?php

namespace App\Http\Controllers\v1;

use App\Http\commen\Common;
use App\Model\UserModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

class LoginController extends BaseController
{
    //        登陆接口
    public function login(Request $request){
//        获取用户信息
        $avatarUrl = $request ->get('avatarUrl');
        $nickName = $request ->get('nickName');
        $gender = $request ->get('gender');
        $token = $request ->header('token');

       $uuid =  Cache::get($token)['uuid'];

       $res =  (new UserModel()) ->login($uuid,$avatarUrl,$nickName,$gender);

       if( $res['code'] ){
            return $this ->success('登陆成功',$res['data']);
       }else{
            return $this->error('失败',$res['data']);
       }



    }


    /**
     * 获取得到openid 返回token
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getToken(Request $request){

        $code = $request ->get('code');

        if(empty($code)){
            return $this -> error('缺少参数！');
        }

        $APP_ID = env('APP_ID');
        $AppSecret= env('AppSecret');
       $url = "https://api.q.qq.com/sns/jscode2session?appid={$APP_ID}&secret={$AppSecret}&js_code={$code}&grant_type=authorization_code";


        try {
            $data = (new Common())->getUrl($url);
        } catch (\Exception $e) {
            $this -> error('获取code错误！');
        }


//        插入数据返回状态
        $res =  (new UserModel()) -> getToken($data);
       if ( $res['code'] ){
//           获取token 添加缓存
           $token =  Common::getStringToken($data ->openid);//获取token
          Cache::put($token,[
              'uuid' => $res['data']['id'],
              'score' => $res['data']['score']//普通权限
          ],env('TOKEN_TIME'));

          return $this ->success('获取token成功',$token);

       }else{
          return  $this ->error('获取token失败！');
       }





    }

}
